import {
    SET_WEEKLY
} from '../mutation-types';
import api from '../../api';

// import { errFun } from "../../tools.js"

const state = {
    weekly: null,
}

function forTime(time) {
    return time > 3600 ? (Math.round(time / 3600)) : (Math.round(time / 60))
}

function forChart(arr) {
    for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].toFixed(0);
    }
    return arr;
}

// 时间戳转格式化时间
Date.prototype.Format = function(fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

const mutations = {
    [SET_WEEKLY](state, data) {
        data.chart.kcals = forChart(data.chart.kcals);
        data.timestamp.start = new Date(data.timestamp.start).Format("M月dd日");
        data.timestamp.end = new Date(data.timestamp.end).Format("M月dd日");
        state.weekly = data;
        if (data.totalKcal != null) {
            state.weekly.totalKcal = Math.floor(data.totalKcal);
        }
        if (data.rate != null) {
            state.weekly.rate.body = data.rate.body.toFixed(0);
            state.weekly.rate.leftArm = data.rate.leftArm.toFixed(0);
            state.weekly.rate.rightArm = data.rate.rightArm.toFixed(0);
            state.weekly.rate.leftLeg = data.rate.leftLeg.toFixed(0);
            state.weekly.rate.rightLeg = data.rate.rightLeg.toFixed(0);
        }

    }

}

const actions = {
    GET_WEEKLY: ({ commit, dispatch }) => {

        //  dispatch('CHANGE_LOADING_SHOW').then(
        api.getWeekly().then(response => {
                //console.log(response.data);
                // console.log(response.data.code)
                commit(SET_WEEKLY, response.data.result);

                //  dispatch('HIDDEN_LOADING_SHOW')
            })
            //  )
    },
    GET_WEEKLY_BY: ({ commit, dispatch }, id) => {

        //  dispatch('CHANGE_LOADING_SHOW').then(
        api.getWeeklyByid(id).then(response => {
                //console.log(response.data);
                // console.log(response.data.code)
                commit(SET_WEEKLY, response.data.result);

                //  dispatch('HIDDEN_LOADING_SHOW')
            })
            //  )
    },

}


export default {
    state,
    actions,
    mutations
}